const express = require("express");
const router = express.Router();
const pool = require("../pool.js");
const utils = require("../utils/index.js");
const moment = require("moment-timezone");
const androidPublisherConn = require("../google/googleapis"); // './publisher' 是该文件的路径
const axios = require("axios");
const config = require("../config");
const msgUtils = require("../utils/feishu.js");

// 引入uuid模块
const { v4: uuidv4 } = require("uuid");
//获取包列表
router.post("/listPackageData", async (req, res) => {
    let { name } = await utils.getUserInfo(req, res);
    let arr = []
    if (name == 'zj_huangweijie') {
        arr = [
            {
                package_name: "roku.remote.control.tv.remotecontrol",
            },
            {
                package_name: "ins.freevideodownload.pro",
            },
        ];
    } else if (name == 'zj_niuyuheng' || name == 'zj_zhangzhiwen') {
        arr = [
            {
                package_name: "ins.freevideodownload.pro",
            },
            {
                package_name: "roku.remote.control.tv.remotecontrol",
            },
        ];
    } else if (name == 'zj_luqi') {
        arr = [
            {
                package_name: "roku.remote.control.tv.remotecontrol",
            }
        ];
    } else if (name == 'zj_qimengru' || name == 'zj_yuanxi') {
        arr = [
            {
                package_name: "ins.freevideodownload.pro",
            }
        ];
    } else {
        arr = [
            {
                package_name: "download.video.downloader.videodownloader.mp4",
            },
            {
                package_name: "com.ai.chat.bot.aichat",
            },
            {
                package_name: "com.ai.chat.bot.aichat.lite",
            },
            {
                package_name: "ins.freevideodownload.pro",
            },
            {
                package_name: "instasave.reels.video.story.ig.instagram.download",
            },
            {
                package_name: "print.smart.printer.pdf.docs.scanner",
            },
            {
                package_name: "food.scanner.calorie.counter.cal.ai",
            },

            // {
            //     package_name: "tv.roku.remote.control.tvremote",
            // },
            // {
            //     package_name: "tv.remote.firetv.firestick",
            // },
            // {
            //     package_name: "samsung.remote.control.samsungtv",
            // },
            // {
            //     package_name: "tv.remote.control.lg.tvremote",
            // },
            {
                package_name: "download.video.downloader.videodownloader.instagram",
            },
            {
                package_name: "roku.remote.control.tv.remotecontrol",
            },
            // {
            //     package_name: "scan.qr.code.barcode.scanner",
            // },
        ];
    }

    // let obj = req.body;
    // let { page, size } = utils.pageSize(obj.page, obj.size);
    // let sql = `SELECT package_name FROM js_app_comment GROUP BY package_name LIMIT ?, ?`;
    // let totalSql = `SELECT COUNT(DISTINCT package_name) AS total_unique_package_names FROM js_app_comment;`;
    // let total = 0;
    // await pool.query(totalSql, (error, results, fields) => {
    //   total = results[0].total_unique_package_names;
    // });
    // await pool.query(sql, [page, size], (err, result) => {
    //   if (err) return res.send(utils.returnData({ code: -1, err, req }));
    //   let data = utils.mapPackageNamesToShortNames(result);
    //   res.send({
    //     code: 0,
    //     msg: "操作成功",
    //     data: data,
    //     total: total,
    //   });
    // });

    res.send({
        code: 0,
        msg: "操作成功",
        data: utils.mapPackageNamesToShortNames(arr),
        total: arr.length,
    });
});

//查询某个包下的评论列表
router.post("/findCommentList", async (req, res) => {
    let { page, size } = utils.pageSize(req.body.page, req.body.size);

    const {
        reviewer_language,
        star_rating,
        app_version_name,
        dateRange,
        package_name,
        is_reply,
        is_five,
        type_id,
    } = req.body;
    let sql = `FROM js_app_comment WHERE package_name = ? and state=0`;

    let params = [package_name];

    if (reviewer_language) {
        sql += ` AND reviewer_language = ?`;
        params.push(reviewer_language);
    }
    if (type_id) {
        sql += ` AND type_id = ?`;
        params.push(type_id);
    }
    if (star_rating) {
        sql += ` AND star_rating = ?`;
        params.push(star_rating);
    }

    if (app_version_name) {
        sql += ` AND app_version_name = ?`;
        params.push(app_version_name);
    }

    if (dateRange && dateRange.start && dateRange.end) {
        sql += ` AND last_modified BETWEEN ? AND ?`;
        params.push(dateRange.start, dateRange.end);
    }

    if (is_reply !== undefined) {
        sql += ` AND is_reply = ?`;
        params.push(is_reply);
    }

    if (is_five == 1) {
        sql += ` AND star_rating = 5`;
    } else if (is_five == 0) {
        sql += ` AND star_rating < 5`;
    }
    // 统计总条数的SQL
    let sqlCount = `SELECT COUNT(*) AS total_count ${sql}`;
    // 查询数据的SQL
    let sqlSelect = `SELECT * ${sql} ORDER BY update_date DESC`;
    let { total } = await utils.getListSum(sqlCount, params, res, req);
    sqlSelect += ` LIMIT ? OFFSET ?`;
    params.push(size, page);
    await pool.query(sqlSelect, params, (err, result) => {
        if (err) return res.send(utils.returnData({ code: -1, err, req }));
        result.forEach((element) => {
            element.create_date = moment(element.create_date)
                .tz("Asia/Shanghai")
                .format("YYYY-MM-DD HH:mm:ss");
            element.update_date = moment(element.update_date)
                .tz("Asia/Shanghai")
                .format("YYYY-MM-DD HH:mm:ss");
        });
        res.send(
            utils.returnData({
                data: result,
                total: total,
            })
        );
    });
});

//不分页的评论列表
router.post("/findCommentListAll", async (req, res) => {
    const {
        reviewer_language,
        star_rating,
        app_version_name,
        dateRange,
        package_name,
        is_reply,
        is_five,
    } = req.body;
    let sql = `FROM js_app_comment WHERE package_name = ?`;
    let params = [package_name];

    if (reviewer_language) {
        sql += ` AND reviewer_language = ?`;
        params.push(reviewer_language);
    }
    if (star_rating) {
        sql += ` AND star_rating = ?`;
        params.push(star_rating);
    }
    if (app_version_name) {
        sql += ` AND app_version_name = ?`;
        params.push(app_version_name);
    }
    if (dateRange && dateRange.start && dateRange.end) {
        sql += ` AND last_modified BETWEEN ? AND ?`;
        params.push(dateRange.start, dateRange.end);
    }
    if (is_reply !== undefined) {
        sql += ` AND is_reply = ?`;
        params.push(is_reply);
    }
    if (is_five == 1) {
        sql += ` AND star_rating = 5`;
    } else if (is_five == 0) {
        sql += ` AND star_rating < 5`;
    }

    // 查询数据的SQL
    let sqlSelect = `SELECT * ${sql} ORDER BY last_modified DESC`;

    await pool.query(sqlSelect, params, async (err, result) => {
        if (err) return res.send(utils.returnData({ code: -1, err, req }));

        // 创建一个包含所有异步操作的 Promise 数组
        let promises = result.map(async (element) => {
            element.create_date = moment(element.create_date)
                .tz("Asia/Shanghai")
                .format("YYYY-MM-DD HH:mm:ss");
            element.update_date = moment(element.update_date)
                .tz("Asia/Shanghai")
                .format("YYYY-MM-DD HH:mm:ss");
            if (element.template_content_id) {
                element.template_type = await getTempType(element.template_content_id);
            }
            return element; // 返回处理后的 element
        });

        // 等待所有异步操作完成，并获得结果数组
        let updatedResult = await Promise.all(promises);

        res.send(
            utils.returnData({
                data: updatedResult, // 返回更新后的结果
            })
        );
    });

});
async function getTempType(template_content_id) {
    return new Promise((resolve, reject) => {
        let sql = `SELECT * FROM js_app_comment_template WHERE id =  '${template_content_id}'`;
        pool.query(sql, (error, results, fields) => {
            if (error) {
                return reject(error);
            }
            let sql1 = `SELECT * FROM js_app_comment_type WHERE id =  '${results[0].type_id}'`
            pool.query(sql1, (error1, results1, fields1) => {
                if (error1) {
                    return reject(error1);
                }
                resolve(results1[0].comment_type);
            });
        });
    });
}
//获取语种列表
router.post("/selectLanguage", async (req, res) => {
    let sql = `SELECT reviewer_language FROM js_app_comment GROUP BY reviewer_language;`;
    await pool.query(sql, (err, result) => {
        if (err) return res.send(utils.returnData({ code: -1, err, req }));
        res.send(
            utils.returnData({
                data: result,
            })
        );
    });
});

//获取app版本
router.post("/selectversionList", async (req, res) => {
    const { package_name } = req.body;
    let sql = `select app_version_name from js_app_comment WHERE package_name = ? group by app_version_name;`;
    await pool.query(sql, [package_name], (err, result) => {
        if (err) return res.send(utils.returnData({ code: -1, err, req }));
        res.send(
            utils.returnData({
                data: result,
            })
        );
    });
});

//查询模板类型列表
router.post("/selectTemplateTypeList", async (req, res) => {
    let { page, size } = utils.pageSize(req.body.page, req.body.size);
    const { package_name } = req.body;
    let sql = `SELECT * FROM js_app_comment_type WHERE package_name = ? AND status = 0 ORDER BY update_date DESC LIMIT ? OFFSET ?`;
    let { total } = await utils.getSum({
        name: "js_app_comment_type",
        where: `WHERE package_name ="${package_name}" AND status = 0`,
        res,
        req,
    });
    await pool.query(sql, [package_name, size, page], (err, result) => {
        if (err) return res.send(utils.returnData({ code: -1, err, req }));
        res.send(
            utils.returnData({
                data: result,
                total: total,
            })
        );
    });
});

//新增或更改类型
router.post("/saveTemplateType", async (req, res) => {
    let { name } = await utils.getUserInfo(req, res);
    const { package_name, id, comment_type } = req.body;
    let appCommentType = {};
    if (id) {
        // 更新
        let sql = `UPDATE js_app_comment_type SET comment_type = '${comment_type}' , update_date = '${utils.formatDate(
            new Date()
        )}' WHERE id = '${id}'`;
        await pool.query(sql, (updateErr, updateResult) => {
            if (updateErr)
                return res.send(utils.returnData({ code: -1, updateErr, req }));
            res.send({ msg: "修改成功" });
        });
    } else {
        //新增
        appCommentType.id = utils.createId();
        appCommentType.package_name = package_name;
        appCommentType.comment_type = comment_type;
        appCommentType.create_by = name;
        appCommentType.update_by = name;
        appCommentType.create_date = utils.formatDate(new Date());
        appCommentType.update_date = utils.formatDate(new Date());
        const { text, values } = utils.createInsertSql(
            "js_app_comment_type",
            appCommentType
        );
        let result = await utils.query(text, values);
        if (result.affectedRows == 1) {
            res.send({ msg: "新增成功" });
        } else {
            res.send(utils.returnData({ code: -1, err, req }));
        }
    }
});

//删除模板类型
router.post("/deleteTemplateType", async (req, res) => {
    let { name } = await utils.getUserInfo(req, res);
    const { package_name, id, comment_type } = req.body;
    // 更新
    let sql = `UPDATE js_app_comment_type SET status = 1, update_by='${name}', update_date = '${utils.formatDate(
        new Date()
    )}' WHERE id = '${id}'`;
    await pool.query(sql, (updateErr, updateResult) => {
        if (updateErr)
            return res.send(utils.returnData({ code: -1, updateErr, req }));
        res.send({ msg: "删除成功" });
    });
});

//查询普通模板
router.post("/selectTemplate", async (req, res) => {
    let { page, size } = utils.pageSize(req.body.page, req.body.size);
    const { package_name, type_id, reviewer_language, template_content } =
        req.body;
    let sqlConditions = [];
    const sqlParams = [];

    if (type_id) {
        sqlConditions.push("type_id = ?");
        sqlParams.push(type_id);
    }
    if (reviewer_language) {
        sqlConditions.push("reviewer_language = ?");
        sqlParams.push(reviewer_language);
    }
    if (template_content) {
        sqlConditions.push("template_content LIKE ?");
        sqlParams.push(`%${template_content}%`);
    }

    let sqlBase = `SELECT * FROM js_app_comment_template WHERE package_name = ? AND status = 0 AND type_id IS NOT NULL AND type_id <> ''`;
    if (sqlConditions.length > 0) {
        sqlBase += " AND " + sqlConditions.join(" AND ");
    }
    sqlBase += " ORDER BY update_date DESC LIMIT ? OFFSET ?";

    sqlParams.unshift(package_name);
    sqlParams.push(size, page);

    let whereConditions = `WHERE package_name = "${package_name}" AND status = 0 AND type_id IS NOT NULL AND type_id <> ''`;

    if (type_id) {
        whereConditions += ` AND type_id = "${type_id}"`;
    }
    if (reviewer_language) {
        whereConditions += ` AND reviewer_language = "${reviewer_language}"`;
    }
    if (template_content) {
        whereConditions += ` AND template_content LIKE "%${template_content}%"`;
    }
    let { total } = await utils.getSum({
        name: "js_app_comment_template",
        where: whereConditions,
        res,
        req,
    });
    await pool.query(sqlBase, sqlParams, (err, result) => {
        if (err) return res.send(utils.returnData({ code: -1, err, req }));
        res.send(
            utils.returnData({
                data: result,
                total: total,
            })
        );
    });
});

//新增或更改模板
router.post("/saveTemplate", async (req, res) => {
    let { name } = await utils.getUserInfo(req, res);
    const { package_name, id, type_id, template_content, reviewer_language } =
        req.body;
    let appCommentType = {};
    if (id) {
        // 更新
        let sql = `UPDATE js_app_comment_template 
           SET type_id = ?, 
               reviewer_language = ?, 
               template_content = ?, 
               update_date = ? 
           WHERE id = ?`;

        // 格式化更新日期
        let updateDate = utils.formatDate(new Date());

        // 使用参数数组替代直接拼接
        let params = [type_id, reviewer_language, template_content, updateDate, id];

        pool.query(sql, params, (updateErr, updateResult) => {
            if (updateErr) {
                console.log(updateErr);
                return res.send(utils.returnData({ code: -1, updateErr, req }));
            }
            res.send({ msg: "修改成功" });
        });
        console.log(sql)
    } else {
        //新增
        appCommentType.id = utils.createId();
        appCommentType.package_name = package_name;
        appCommentType.type_id = type_id;
        appCommentType.template_content = template_content;
        appCommentType.reviewer_language = reviewer_language;
        appCommentType.create_by = name;
        appCommentType.update_by = name;
        appCommentType.status = 0;
        appCommentType.create_date = utils.formatDate(new Date());
        appCommentType.update_date = utils.formatDate(new Date());
        const { text, values } = utils.createInsertSql(
            "js_app_comment_template",
            appCommentType
        );
        let result = await utils.query(text, values);
        if (result.affectedRows == 1) {
            res.send({ msg: "新增成功" });
        } else {
            res.send(utils.returnData({ code: -1, err, req }));
        }
    }
});

//删除模板
router.post("/deleteTemplate", async (req, res) => {
    let { name } = await utils.getUserInfo(req, res);
    const { package_name, id, comment_type } = req.body;
    // 更新
    let sql = `UPDATE js_app_comment_template SET status = 1 ,update_by='${name}', update_date = '${utils.formatDate(
        new Date()
    )}' WHERE id = '${id}'`;
    await pool.query(sql, (updateErr, updateResult) => {
        if (updateErr)
            return res.send(utils.returnData({ code: -1, updateErr, req }));
        res.send({ msg: "删除成功" });
    });
});

//查询五星模板
router.post("/selectTemplateFive", async (req, res) => {
    let { page, size } = utils.pageSize(req.body.page, req.body.size);
    const { package_name, template_content, status } = req.body;
    let sqlConditions = [];
    const sqlParams = [];
    if (status) {
        sqlConditions.push("status = ?");
        sqlParams.push(status);
    }
    if (template_content) {
        sqlConditions.push("template_content LIKE ?");
        sqlParams.push(`%${template_content}%`);
    }

    let sqlBase = `SELECT * FROM js_app_comment_template WHERE package_name = ? AND status <> 1 AND (type_id IS NULL OR type_id = '')`;
    if (sqlConditions.length > 0) {
        sqlBase += " AND " + sqlConditions.join(" AND ");
    }
    sqlBase += " ORDER BY update_date DESC LIMIT ? OFFSET ?";
    sqlParams.unshift(package_name);
    sqlParams.push(size, page);

    let whereConditions = `WHERE package_name = "${package_name}" AND status <> 1 AND (type_id IS NULL OR type_id = '')`;

    if (template_content) {
        whereConditions += ` AND template_content LIKE "%${template_content}%"`;
    }
    let { total } = await utils.getSum({
        name: "js_app_comment_template",
        where: whereConditions,
        res,
        req,
    });
    await pool.query(sqlBase, sqlParams, (err, result) => {
        if (err) return res.send(utils.returnData({ code: -1, err, req }));
        res.send(
            utils.returnData({
                data: result,
                total: total,
            })
        );
    });
});

//新增或更改五星模板
router.post("/saveTemplateFive", async (req, res) => {
    let { name } = await utils.getUserInfo(req, res);
    const { package_name, id, template_content, reviewer_language } = req.body;
    let appCommentType = {};
    if (id) {
        // 更新
        let sql = `UPDATE js_app_comment_template SET  reviewer_language = '${reviewer_language}' ,template_content = '${template_content}' , update_date = '${utils.formatDate(
            new Date()
        )}' WHERE id = '${id}'`;
        await pool.query(sql, (updateErr, updateResult) => {
            if (updateErr)
                return res.send(utils.returnData({ code: -1, updateErr, req }));
            res.send({ msg: "修改成功" });
        });
    } else {
        //新增
        appCommentType.id = utils.createId();
        appCommentType.package_name = package_name;
        appCommentType.template_content = template_content;
        appCommentType.reviewer_language = reviewer_language;
        appCommentType.create_by = name;
        appCommentType.update_by = name;
        appCommentType.status = 2;
        appCommentType.create_date = utils.formatDate(new Date());
        appCommentType.update_date = utils.formatDate(new Date());
        const { text, values } = utils.createInsertSql(
            "js_app_comment_template",
            appCommentType
        );
        let result = await utils.query(text, values);
        if (result.affectedRows == 1) {
            res.send({ msg: "success" });
        } else {
            res.send(utils.returnData({ code: -1, err, req }));
        }
    }
});

//模板的启用禁用
router.post("/setTemplateStatus", async (req, res) => {
    let { name } = await utils.getUserInfo(req, res);
    const { id, status } = req.body;
    const newStatus = status == "0" ? 2 : 0;
    // 更新
    let sql = `UPDATE js_app_comment_template 
             SET status = ?, update_date = ?, update_by = ? 
             WHERE id = ?`;
    let values = [newStatus, utils.formatDate(new Date()), name, id];
    await pool.query(sql, values, (updateErr, updateResult) => {
        if (updateErr)
            return res.send(utils.returnData({ code: -1, updateErr, req }));
        res.send({ msg: "success" });
    });
});

//根据不同环境 去调用回复函数

router.post("/respondBasedOnContext", async (req, res) => {
    let urlRequest = "";
    const { package_name, token } = req.body;
    switch (package_name) {
        case config.INS1:
            urlRequest = "http://45.76.212.42:5000/node/appComment/replyComment";
            break;
        case config.INS2:
        case config.ALL:
        case config.ALL2:
        case config.androidRoku2:
        case config.androidRoku3:
        case config.androidCalorie:
        case config.androidPrint:
            urlRequest = "https://fd.freevideodownload.pro/node/appComment/replyComment";
            break;
        case config.PDF:
        case config.INS3:
        case config.STEPCOUNTER:
        case config.WA2:
        case config.WA3:
            urlRequest = "http://172.104.35.128:5000/node/appComment/replyComment";
            break;
        case config.CALCULATOR:
            urlRequest = "http://192.46.226.198:5000/node/appComment/replyComment";
            break;
        case config.CHAT1:
        case config.CHAT2:
        case config.CHAT5:
        case config.androidSamsung:
        case config.androidRoku:
        case config.androidLG:
        case config.androidFiretv:
            urlRequest = "http://139.177.190.31:5000/node/appComment/replyComment";
            break;
        default:
            console.info("Package name does not match any known keys");
            return null;
    }
    if (urlRequest) {
        try {
            const response = await axios.post(urlRequest, req.body, {
                headers: {
                    "Content-Type": "application/json",
                    Token: token,
                },
                timeout: 180000, // 设置超时时间为180秒
            });
            if (
                response.data &&
                response.data.code == 200 &&
                response.data.msg == "success"
            ) {
                res.json({ code: 200, message: "success" });
            } else {
                res.json(response.data); //返回具体的失败响应
            }
        } catch (error) {
            console.error("request error please view log:", error.message);
            return res.send({ code: -1, msg: error.message });
        }
    } else {
        console.error("urlRequest is empty.");
        return res.send({ code: -1, msg: "urlRequest is empty" });
    }
});
async function mysqlQuery(sql,arr) {
    return new Promise((resolve, reject) => {
        pool.query(sql, arr, (error, results, fields) => {
            if (error) {
                return reject(error);
            }
            resolve(results);
        });
    });
}
//查询模板类型

router.post('/getTemplateTypeById', async (req, res) => {
    const { pk, template_content_id } = req.body
    const sql = 'select * from js_app_comment_template where package_name = ? and id = ?';
    const params = [pk, template_content_id];  
    const results = await mysqlQuery(sql, params);
    let arr = []
    let sqls = `select * from js_app_comment_type where package_name = ? and id = ?`
    if (results.length > 0) {
        arr = await mysqlQuery(sqls, [pk, results[0].type_id])

    }
    res.send(
        utils.returnData({
            data: arr
        })
    );
})
//回复评论
router.post("/replyComment", async (req, res) => {

    let { name } = await utils.getUserInfo(req, res);
    // 1.接收传递过来的参数
    const { package_name, reply_content, review_id, template_content_id ,type_id,type_name} =
        req.body;
    console.log(`---------执行手动回复---------,包名${package_name},当前所在服务器-----------${process.env.HOSTNAME}`)
    // 2.创建google api 链接 const androidPublisher = await androidPublisherConn(packageName);
    const androidPublisher = await androidPublisherConn(package_name);
    // 创建评论回复
    const reply = {
        replyText: reply_content,
    };
    try {
        const response = await androidPublisher.reviews.reply({
            packageName: package_name,
            reviewId: review_id,
            requestBody: reply,
        });

        const replyRes = JSON.stringify(response.data);
        if (replyRes.includes("replyText")) {
            //成功  存入数据库
            // 通过review_id 查
            let comment = {};
            comment.reply_content = reply_content;
            comment.reply_id = uuidv4().replace(/-/g, "");
            comment.reply_date = utils.formatDate(new Date());
            comment.update_by = name;
            comment.update_date = utils.formatDate(new Date());
            comment.is_reply = 1;
            comment.template_content_id = template_content_id;
            comment.type_id = type_id;
            comment.type_name = type_name;
            // 更新js_app_comment表中匹配review_id的记录
            let sqlUpdate = `UPDATE js_app_comment SET type_id = ?,type_name = ?,reply_content = ?, reply_id = ?, reply_date = ?, update_by = ?, update_date = ?, is_reply = ?, template_content_id = ? WHERE review_id = ?`;
            let valuesUpdate = [
                comment.type_id,
                comment.type_name,
                comment.reply_content,
                comment.reply_id,
                comment.reply_date,
                comment.update_by,
                comment.update_date,
                comment.is_reply,
                comment.template_content_id,
                review_id,
            ];
            await pool.query(sqlUpdate, valuesUpdate, (updateErr, updateResult) => {
                if (updateErr)
                    return res.send(utils.returnData({ code: -1, updateErr, req }));
                res.send({ code: 200, msg: "success" });
            });
            // res.json({ code: 200, message: "Reply successful" });
        } else {
            return res.send({ code: -1, msg: "操作失败" });
        }
        console.log("reviewsReply res: -------回复评论", replyRes);

    } catch {
         
        // 更新js_app_comment表中匹配review_id的记录
        let sqlUpdate = `UPDATE js_app_comment SET state = 1  WHERE review_id = ?`;
        let valuesUpdate = [
            review_id
        ];
        await pool.query(sqlUpdate, valuesUpdate, (updateErr, updateResult) => {
            if (updateErr) return  
                
        });
        return res.send({ code: -1, msg: "评论已被删除" });

    }
});
// 在路由文件中定义函数
async function replyCommentHandel(comment) {
    // ... 获取用户信息、接收参数、调用Google API等逻辑
    // 返回处理结果
}
router.post("/test", async (req, res) => {
    console.log('进')
    res.send({ msg:'接口部署成功'})
});
// 上传图片到飞书
async function uploadImage(url, token) {
    // 将图片 URL 转换为二进制流
    const binaryImage = await urlToBinary(url);
    const response = await axios({
        method: 'post',
        url: 'https://open.feishu.cn/open-apis/im/v1/images',
        headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'multipart/form-data'
        },
        data: {
            image_type: 'message',
            image: binaryImage // 这里需要是图片的 base64 编码
        }
    });
    return response.data.data.image_key;
}
async function urlToBinary(url) {
    const response = await axios.get(url, { responseType: 'arraybuffer' });
    return response.data;
}
module.exports = router;
